package org.example.wx.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.common.utils.ResponseUtil;
import org.example.db.entity.Cart;
import org.example.wx.dto.GoodsGeneralDto;
import org.example.wx.dto.GoodsIdGoodsSpecIdDto;
import org.example.wx.dto.OrderDto;
import org.example.wx.service.WxCartService;
import org.example.wx.service.WxGoodsService;
import org.example.wx.service.WxOrderService;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

@RestController
@Api(tags = "购物车")
@RequestMapping("/wx/cart")
public class WxCartController {

    WxCartService wxCartService;
    WxGoodsService wxGoodsService;
    WxOrderService wxOrderService;

    public WxCartController(WxCartService wxCartService, WxGoodsService wxGoodsService, WxOrderService wxOrderService) {
        this.wxCartService = wxCartService;
        this.wxGoodsService = wxGoodsService;
        this.wxOrderService = wxOrderService;
    }

    @PostMapping("/add")
    @ApiOperation("购物车增加商品")
    public Object add(@RequestBody GoodsIdGoodsSpecIdDto cartMsg){

        wxCartService.addCart(cartMsg);
        return ResponseUtil.ok();
    }

    @GetMapping("/list")
    @ApiOperation("购物车列表")
    public Object list(){
        List<Cart> carts = wxCartService.listCart();
        LinkedList<GoodsGeneralDto> goodsGeneralDtoLinkedList = new LinkedList<>();
        for(Cart cart: carts){
            GoodsGeneralDto goodsGeneral = wxGoodsService.getGoodsGeneral(cart.getGoodsSpecId(), cart.getNumber());
            goodsGeneralDtoLinkedList.add(goodsGeneral);
        }
        return ResponseUtil.ok(goodsGeneralDtoLinkedList);
    }

    /**
     *
     * @param id goodsSpecificationId
     * @return /
     */
    @GetMapping("/delete")
    @ApiOperation("删除购物车商品")
    public Object delete(@RequestParam Long id){
        wxCartService.deleteCart(id);
        return ResponseUtil.ok();
    }

    @PostMapping("/submit")
    @ApiOperation("提交购物车")
    public Object post(@RequestBody List<GoodsGeneralDto> list){

        LinkedList<OrderDto> orderDtoLinkedList = new LinkedList<>();
        for(GoodsGeneralDto goodsGeneralDto: list){

            orderDtoLinkedList.add(new OrderDto(null, goodsGeneralDto.getSpecificationId(), goodsGeneralDto.getNumber()));
            wxCartService.deleteCart(goodsGeneralDto.getSpecificationId());
        }
        wxOrderService.addOrder(orderDtoLinkedList);

        return null;
    }


    @GetMapping("/number")
    @ApiOperation("购物车商品数量")
    public Object number(){

        int i = wxCartService.cartCount();
        return ResponseUtil.ok(i);
    }
}
